import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { postHttp } from '../../request/api';
import JSEncrypt from 'jsencrypt';

interface LoginForm {
    email: string;
    password: string;
}

interface DoctorInfo {
    doctorId: number;
    sessionId: string;
    name: string;
    userName: string;
    reviewStatus: number;
    imagePic: string;
    inauguralHospital: string;
    jobTitle: string;
    departmentId: number;
    departmentName: string;
}

interface AuthState {
    doctorInfo: DoctorInfo | null;
    loading: boolean;
    error: string | null;
}

const initialState: AuthState = {
    doctorInfo: null,
    loading: false,
    error: null,
};

const publicKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuQd3gESx7VdIyRYUWjmjg61VIgUK6F45hClmqUMZ7xNiT5rlLM6e78osMvBF/yP7cVm7pK+NMCDWoVS1/AETpxJYqUlIC77ZAU8/MnP96IupnJL87vqhPcpdv7+VqLM38ls++yuD/F/HSoOQTv/leJh+dgE/4EYAJjOWFAbYfXwIDAQAB`;

const encryptedData = (publicKey: string, data: string) => {
    const encryptor = new JSEncrypt();
    encryptor.setPublicKey(publicKey);
    return encryptor.encrypt(data);
};

export const login = createAsyncThunk(
    'auth/login',
    async (values: LoginForm, { rejectWithValue }) => {
        try {
            const value = {
                email: values.email,
                pwd: encryptedData(publicKey, values.password)
            };
            
            const response = await postHttp('/health/doctor/v1/login', value);
            const res = response.data;
            
            if (res.status === '0000') {
                const doctorInfo = {
                    doctorId: res.result.doctorId,
                    sessionId: res.result.sessionId,
                    name: res.result.name,
                    userName: res.result.userName,
                    reviewStatus: res.result.reviewStatus,
                    imagePic: res.result.imagePic,
                    inauguralHospital: res.result.inauguralHospital,
                    jobTitle: res.result.jobTitle,
                    departmentId: res.result.departmentId,
                    departmentName: res.result.departmentName
                };
                
                localStorage.setItem('doctorInfo', JSON.stringify(doctorInfo));
                return { doctorInfo, whetherHaveImagePic: res.result.whetherHaveImagePic };
            } else {
                return rejectWithValue(res.message || '登录失败');
            }
        } catch (error) {
            return rejectWithValue('登录失败，请稍后重试');
        }
    }
);

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        logout: (state) => {
            state.doctorInfo = null;
            localStorage.removeItem('doctorInfo');
        },
        clearError: (state) => {
            state.error = null;
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(login.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(login.fulfilled, (state, action) => {
                state.loading = false;
                state.doctorInfo = action.payload.doctorInfo;
            })
            .addCase(login.rejected, (state, action) => {
                state.loading = false;
                state.error = action.payload as string;
            });
    },
});

export const { logout, clearError } = authSlice.actions;
export default authSlice.reducer; 